package com.anhry.app.safety.manage.system.struts.action;

import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.anhry.app.safety.manage.system.bean.TbLoginLog;
import com.anhry.app.safety.manage.system.bean.TbUser;
import com.anhry.app.safety.manage.system.struts.base.SystemBaseAction;
import com.anhry.app.safety.util.DateFormater;
import com.anhry.app.safety.util.Loggers;
import com.anhry.app.safety.util.OnlineUser;
import com.anhry.app.safety.util.OnlineUsers;
import com.anhry.app.safety.util.Util;
import com.anhry.app.safety.util.UtilMethod;
import com.anhry.app.safety.util.online.ApplicationConstants;
import com.opensymphony.xwork2.ActionContext;


/**
 * @date:2012-5-15
 * @remark:
 * @author:dongbin
 */
@Controller
@Scope("prototype")
public class LoginAction extends SystemBaseAction{

	private Logger logger  = Logger.getLogger(LoginAction.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String loginName;
	private String password;
	private String rand;
	
	public String execute(){
		TbUser user = null;
		TbUser sesseonUser = (TbUser)this.contextPvd.getSessionAttr(Util.SESSION_ADMINUSER);
		try {	
			
			String url = this.contextPvd.getRequestURL();//访问网址
			String param = this.contextPvd.getRequest().getQueryString();//参数
			if(UtilMethod.urlFilter(url) || UtilMethod.urlFilter(param)){
				return "error";
			}
			if(null==this.loginName || "".equals(this.loginName)){
				this.setTip("用户名输入错误，系统无此用户名！");
				return INPUT;
			}
			//验证码
			if(this.contextPvd.getSessionAttr("rand") != null && !this.getRand().equalsIgnoreCase(this.contextPvd.getSessionAttr("rand").toString())){
				this.setTip("验证码错误，请重新输入！");
				return INPUT;
			}	
			this.contextPvd.getSession().removeAttribute("rand");
			OnlineUser u = (OnlineUser)this.contextPvd.getSessionAttr("currentUser");//记录上线用户
			if(sesseonUser != null){//用户尚未退出		
				return SUCCESS;
			}
			user = this.systemService.getUserByUserName(this.getLoginName());
			if(user == null){
				this.setTip("用户名输入错误，系统无此用户名！");
				return INPUT;
			}
			user = this.systemService.userLogin(user, this.getPassword());
			if(user != null){
				if(user.getIsLock() != null && "1".equals(user.getIsLock())){
					this.setTip("该用户已锁定，请联系管理员！");
					return INPUT;
				}
				/**
				 * 记录上线用户
				 */
//				this.contextPvd.setSessionAttr("admin_listener", OnlineUsers.getInstance());
				if(u != null){
					u.setName(user.getUserName());
					u.setAddress(this.contextPvd.getRemoteIp());
					u.setLogintime(DateFormater.formatDateTime(new Date()));
					if(user.getTbUserGrade() != null){
						u.setUsertype(user.getTbUserGrade().getGradeName());
					}
					if(user.getTbUserUnit() != null){
						u.setUserUnit(user.getTbUserUnit().getDeptName());
					}else{
						u.setUserUnit("");
					}
					if(user.getTbUserDept() != null){
						u.setUserDept(user.getTbUserDept().getDeptName());
					}else{
						u.setUserDept("");
					}
					if(user.getTbUserStreet() != null){
						u.setUserStreet(user.getTbUserStreet().getDeptName());
					}else{
						u.setUserStreet("");
					}
				}else{
					OnlineUser u1 = new OnlineUser();
					u1.setName(user.getUserName());
					u1.setAddress(this.contextPvd.getRemoteIp());
					u1.setLogintime(DateFormater.formatDateTime(new Date()));
					if(user.getTbUserGrade() != null){
						u1.setUsertype(user.getTbUserGrade().getGradeName());
					}
					if(user.getTbUserUnit() != null){
						u1.setUserUnit(user.getTbUserUnit().getDeptName());
					}else{
						u1.setUserUnit("");
					}
					if(user.getTbUserDept() != null){
						u1.setUserDept(user.getTbUserDept().getDeptName());
					}else{
						u1.setUserDept("");
					}
					if(user.getTbUserStreet() != null){
						u1.setUserStreet(user.getTbUserStreet().getDeptName());
					}else{
						u1.setUserStreet("");
					}
					u1.setId(this.contextPvd.getSession().getId());
					this.contextPvd.getSession().setAttribute("currentUser",u1);
					
					ApplicationConstants.ONLIE_USERS.add(u1);
				}
				/**
				 * 将登录用户放到session中
				 */
				contextPvd.setSessionAttr(Util.SESSION_ADMINUSER, user);
				/**
				 * 记录用户登录信息
				 */
				user.setUserLoginCount(user.getUserLoginCount()+1);
				user.setUserLoginTime(new Date());
				user.setUserLoginIp(this.contextPvd.getRemoteIp());
				this.utilService.update(user);
				/**
				 * 记录日志信息
				 */
				TbLoginLog log = new TbLoginLog();
				log.setLogUserId(user.getId());
				log.setLogUserName(user.getUserName());
				log.setLogRemark("用户登录");
				log.setLoginIP(this.contextPvd.getRemoteIp());
				log.setLogTime(new Date());
				log.setIsDele("0");
				this.utilService.save(log);
				return SUCCESS;
			}else{
				this.setTip("密码输入错误，请重新输入！");
				return INPUT;			
			}
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("manage:LoginAction用户登录错误"+e.getMessage());
		}
		return INPUT;
	}
	
	public boolean setSession(String userName, HttpServlet servlet,
			HttpSession session) {
		boolean isLoggedOn = false;
		final ServletContext sc = servlet.getServletContext();//取得容器,容器中根据用户唯一标识userID存放session  
		if(logger.isDebugEnabled()) {
			System.out.println(sc);
			System.out.println(session);
		}
		if (sc.getAttribute(userName) != null) {
			// 第二次登陆后第一次无效  
			((HttpSession) sc.getAttribute(userName)).invalidate();// 清除第一次登陆的session  
			System.out.println(session);
		}
		sc.setAttribute(userName, session);//放入当前最新session  

		return isLoggedOn;
	}
	
	public String onlineUsers() {
		ActionContext.getContext().put("onlineUses", OnlineUsers.getInstance().getUsers());
		
		return SUCCESS;
	}

	public String getLoginName() {
		return loginName;
	}

	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getRand() {
		return rand;
	}

	public void setRand(String rand) {
		this.rand = rand;
	}

}
